const cloudConfig = require('../../../utils/cloudConfig');

Component({
  properties: {},
  data: {
    BOOK_COVERS_PATH_PREFIX: cloudConfig.BOOK_COVERS_PATH_PREFIX, // 书籍封面URL前缀
    textbooks: [],
    textbookCount: 0,
    totalTextbookWords: 0,
    totalProgress: 0,
    slideStates: {} // 存储滑动状态: { bookId: slideX }
  },
  lifetimes: {
      attached() {
        // 初始化数据管理器 - 使用全局实例
        const app = getApp();
        this.wordDataManager = app.globalData.wordDataManager;
        // 获取屏幕宽度用于rpx转px计算
        const systemInfo = wx.getSystemInfoSync();
        this.setData({
          screenWidth: systemInfo.screenWidth
        });
        this.loadTextbooks();
      }
    },
  // pageLifetimes: {
  //   show() {
  //     // 页面显示时刷新数据
  //     this.loadTextbooks();
  //   }
  // },
  methods: {
      // 拖动结束事件处理
      onDragEnd(e) {
        const { index } = e.currentTarget.dataset;
        const deleteWidth = this.data.deleteWidth || 160; // 默认删除按钮宽度160rpx
        const pxDeleteWidth = deleteWidth * this.data.screenWidth / 750;
        const finalX = e.detail.x;
        
        // 判断最终位置是否超过阈值（10%的删除按钮宽度）
        const triggerThreshold = pxDeleteWidth * 0.1;
        const shouldOpen = finalX < -triggerThreshold;
        const slideX = shouldOpen ? -pxDeleteWidth : 0;
        
        // 更新当前项状态
        // 获取当前书籍ID
          const bookId = this.data.textbooks[index].id;
          
          // 同时更新独立状态和视图数据
          this.setData({
            [`slideStates[${bookId}]`]: slideX,
            [`textbooks[${index}].slideX`]: slideX
          }, () => {
          // 批量关闭其他所有项的删除按钮，减少setData调用
          const updates = {};
          this.data.textbooks.forEach((item, i) => {
            if (i !== index && item.slideX !== 0) {
              updates[`textbooks[${i}].slideX`] = 0;
              updates[`slideStates[${item.id}]`] = 0;
            }
          });
          this.setData(updates);
        });
      },
      
      // 确认删除
      confirmDelete(e) {
        const bookId = e.currentTarget.dataset.id;
        const bookName = e.currentTarget.dataset.name;
        const index = e.currentTarget.dataset.index;
        
        wx.showModal({
          title: '确认删除',
          content: `确定要删除词书${bookName}吗？此操作不可恢复。`,
          confirmColor: '#ff4d4f',
          success: (res) => {
            if (res.confirm) {
              // 调用数据管理器删除词书
              this.wordDataManager.deleteBook(bookId);
              // 重新加载词书列表
              this.loadTextbooks();
              // 显示删除成功提示
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000
              });
            } else {
              // 取消删除，复位滑动状态
              const textbooks = [...this.data.textbooks];
              textbooks[index].slideX = 0;
              this.setData({ textbooks });
            }
          }
        });
      },
      
      onRefresh() {
        console.log('刷新词书列表OnRefresh:');
        this.loadTextbooks();
      },
    loadTextbooks() {
      try {
        const allBooks = this.wordDataManager.getAllBooks();
        const textbooks = allBooks.map(book => {
          const wordCount = book.wordIds.length;
          const bookWords = this.wordDataManager.getWordsByBookId(book.id) || [];
          // 使用WordDataManager的API判断学习状态
          const learnedWords = bookWords.filter(word => {
            return this.wordDataManager.getWordLearnedStatus(word.id);
          }).length;
          const progress = wordCount > 0 ? Math.round((learnedWords / wordCount) * 100) : 0;
          // 保留已有的slideX状态，初始化为0
          // 从独立状态中获取滑动位置
          return { ...book, wordCount, progress, slideX: this.data.slideStates[book.id] || 0 };
        });
        // compute totals
        let totalTextbookWords = 0, totalLearned = 0;
        textbooks.forEach(tb => {
          totalTextbookWords += tb.wordCount;
          totalLearned += Math.round(tb.wordCount * (tb.progress / 100));
        });
        const totalProgress = totalTextbookWords > 0 ? Math.round((totalLearned / totalTextbookWords) * 100) : 0;
        // 排序：将激活的词书(active === 1)排在最前面
      const sortedTextbooks = [...textbooks].sort((a, b) => {
        // 先比较激活状态，激活的排在前面
        if (a.active === 1 && b.active !== 1) return -1;
        if (a.active !== 1 && b.active === 1) return 1;
        // 激活状态相同时，按最后激活时间排序（如果有）
        if (a.lastActiveTime && b.lastActiveTime) {
          return new Date(b.lastActiveTime) - new Date(a.lastActiveTime);
        }
        return 0;
      });

      this.setData({
        textbooks: sortedTextbooks,
        textbookCount: sortedTextbooks.length,
        totalTextbookWords,
        totalProgress
      });
      } catch (e) {
        console.error('加载教材失败', e);
      }
    },
    open(e) {
      const { id } = e.currentTarget.dataset;
      
      wx.navigateTo({ url: `/pages/vocabulary/word-list/word-list?bookId=${id}` });
    },
    learn(e) {
      e.stopPropagation && e.stopPropagation();
      const { id, name } = e.currentTarget.dataset;

      wx.navigateTo({ url: `/pages/vocabulary/learning/learning?bookId=${id}&bookName=${encodeURIComponent(name)}` });
    },
    
    /**
     * 同步单词数据
     * @param {Object} e - 事件对象
     */
    syncWords(e) {
      e.stopPropagation && e.stopPropagation();
      const { id, name, wordcount } = e.currentTarget.dataset;
      
      // 显示确认弹窗
      wx.showModal({
        title: '同步单词数据',
        content: `确定要同步"${name}"的单词详细信息吗？\n\n这将获取${wordcount}个单词的发音、例句等信息。`,
        success: (res) => {
          if (res.confirm) {
            
            // 显示等待框
            wx.showLoading({
              title: '同步中...',
              mask: true
            });
            
            // 同步单词详情
            this.wordDataManager.syncBookWords(id, {
              onProgress: (progress) => {
                // 使用setTopBarText更新进度，避免重复创建loading
                try {
                  // 尝试更新标题栏文本
                  wx.setNavigationBarTitle({
                    title: `同步中: ${progress.processed}/${progress.total}`
                  });
                } catch (e) {
                  console.log('无法更新标题栏', e);
                }
              },
              onComplete: (results) => {
                // 先隐藏加载提示
                wx.hideLoading();
                // 恢复导航栏标题
                wx.setNavigationBarTitle({
                  title: '词书'
                });
                // 显示同步完成提示
                setTimeout(() => {
                  wx.showToast({
                    title: '单词同步完成',
                    icon: 'success',
                    duration: 2000
                  });
                }, 100);
                // 重新加载词书数据以更新同步状态
                this.loadTextbooks();
              },
              onError: (error) => {
                wx.hideLoading();
                // 显示同步失败提示
                wx.showToast({
                  title: '单词同步失败: ' + error.message,
                  icon: 'none',
                  duration: 3000
                });
              }
            });
          }
        }
      });
    }
  }
});
